#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>

#include "thread_functions.h"

int main(void) {
	//先连接数据库
	if (!connect_db()) {
		exit(EXIT_FAILURE);
	}

	int res;
	pthread_t login_thread;
	pthread_t userinfo_thread;
	pthread_t traininfo_thread;
	pthread_t orderinfo_thread;
	int login_port = PORT_LOGIN; //负责接受登录请求线程的端口号
	int userinfo_port = PORT_USERINFO; //负责接受修改个人资料和注册请求的端口号
	int traininfo_port = PORT_TRAININFO; //负责接受与火车相关的各种请求的端口号
	int orderinfo_port = PORT_ORDERINFO; //负责接受与订单相关的各种请求的端口号

	res = pthread_create(&login_thread, NULL, login_thread_function,
			(void *) &login_port);
	if (res != 0) {
		perror("login_thread creation failed\n");
		exit(EXIT_FAILURE);
	}
	res = pthread_create(&userinfo_thread, NULL, userinfo_thread_function,
			(void *) &userinfo_port);
	if (res != 0) {
		perror("userinfo_thread creation failed\n");
		exit(EXIT_FAILURE);
	}
	res = pthread_create(&traininfo_thread, NULL, traininfo_thread_function,
			(void *) &traininfo_port);
	if (res != 0) {
		perror("traininfo_thread creation failed\n");
		exit(EXIT_FAILURE);
	}
	res = pthread_create(&orderinfo_thread, NULL, orderinfo_thread_function,
			(void *) &orderinfo_port);
	if (res != 0) {
		perror("orderinfo_thread creation failed\n");
		exit(EXIT_FAILURE);
	}

	//printf("Waiting for thread to finish...\n");

	void *login_thread_result;
	res = pthread_join(login_thread, &login_thread_result);

	if (res == 0) {
		perror("login_thread joined failed.\n");
		exit(EXIT_FAILURE);
	} else {
		printf(
				"login_thread joined, but it should not be joined because the login_thread should not stop!\n");
		printf("login_thread returned %s\n", (char*) login_thread_result);
	}

	void *userinfo_thread_result;
	res = pthread_join(userinfo_thread, &userinfo_thread_result);
	if (res == 0) {
		perror("userinfo_thread joined failed.\n");
		exit(EXIT_FAILURE);
	} else {
		printf(
				"userinfo_thread joined, but it should not be joined because the userinfo_thread should not stop!\n");
		printf("userinfo_thread returned %s\n", (char*) userinfo_thread_result);
	}

	void *traininfo_thread_result;
	res = pthread_join(traininfo_thread, &traininfo_thread_result);
	if (res == 0) {
		perror("traininfo_thread joined failed.\n");
		exit(EXIT_FAILURE);
	} else {
		printf(
				"traininfo_thread joined, but it should not be joined because the traininfo_thread should not stop!\n");
		printf("traininfo_thread returned %s\n",
				(char*) traininfo_thread_result);
	}

	void *orderinfo_thread_result;
	res = pthread_join(orderinfo_thread, &orderinfo_thread_result);
	if (res == 0) {
		perror("orderinfo_thread joined failed.\n");
		exit(EXIT_FAILURE);
	} else {
		printf(
				"orderinfo_thread joined, but it should not be joined because the orderinfo_thread should not stop!\n");
		printf("orderinfo_thread returned %s\n",
				(char*) orderinfo_thread_result);
	}
	close_connection();
	exit(EXIT_SUCCESS);
}
